package org.example.mock;

import lombok.extern.slf4j.Slf4j;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 用于生成 MovieTypeCount 模拟数据并插入数据库的工具类
 */
@Slf4j
public class MovieTypeCountGenerator {
    private static final String DB_URL = "jdbc:mysql://192.168.10.102/changchengfilm?requireSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String DB_USER = "root"; // 添加数据库用户名
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 100;

    public static void main(String[] args) {
        log.info("开始生成并插入 MovieTypeCount 模拟数据");

        try (Connection conn = getConnection()) {
            // 禁用自动提交，使用事务提高性能
            conn.setAutoCommit(false);

            List<MovieTypeCount> dataList = generateData();
            insertData(conn, dataList);

            // 提交事务
            conn.commit();
            log.info("数据插入成功，共插入 {} 条记录", dataList.size());

        } catch (SQLException e) {
            log.error("数据库操作失败", e);
        }
    }

    /**
     * 获取数据库连接
     */
    private static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }

    /**
     * 生成50条 MovieTypeCount 模拟数据
     */
    private static List<MovieTypeCount> generateData() {
        List<MovieTypeCount> dataList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            MovieTypeCount data = new MovieTypeCount();
            int movieId = i + 1;
            int typeId = (i % 10) + 1;

            data.setMovieId(String.valueOf(movieId));
            data.setTypeId(String.valueOf(typeId));
            dataList.add(data);
        }
        return dataList;
    }

    /**
     * 将数据批量插入数据库
     */
    private static void insertData(Connection conn, List<MovieTypeCount> dataList) throws SQLException {
        String sql = "INSERT INTO movie_type_count (movie_id, type_id) VALUES (?, ?)";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            int count = 0;

            for (MovieTypeCount data : dataList) {
                pstmt.setString(1, data.getMovieId());
                pstmt.setString(2, data.getTypeId());
                pstmt.addBatch();

                // 每BATCH_SIZE条数据执行一次批处理
                if (++count % BATCH_SIZE == 0) {
                    pstmt.executeBatch();
                }
            }

            // 执行剩余的批处理
            pstmt.executeBatch();
        }
    }
}